package com.example.androidcaculator.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.androidcaculator.R;
import com.example.androidcaculator.utils.Calculator;

import java.lang.reflect.Method;

public class ScientificActivity extends AppCompatActivity {

    private Button[] btn = new Button[10];
    private Button add, sub, mul, div, equal, left, right, point,
            square, cube, yPower, root, yRoot, factorial,
            ln, log, sin, cos, tan, percent,
            e, pi, clear, back;

    private TextView result;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scientific);
        initView();
        input = "";
    }

    private String input; //要加到界面中的字符串
    //获取数字的监听器
    private View.OnClickListener actionNum = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String context = ((Button) view).getText().toString();
            if (context.equals("0") && String.valueOf(result.getText()).equals("0")) {
                result.setText("0");
            } else if (context.equals("e")) {
                String value = result.getText().toString();
                char ch = value.charAt(value.length() - 1);
                if (ch == '+' || ch == '-' || ch == '×' || ch == '÷') {
                    input += String.valueOf(Math.E);
                    result.setText(input);
                } else {

                    input = String.valueOf(Math.E);
                    result.setText(input);
                }
            } else if (context.equals("Π")) {
                String value = result.getText().toString();
                char ch = value.charAt(value.length() - 1);

                if (ch == '+' || ch == '-' || ch == '×' || ch == '÷') {
                    input += String.valueOf(Math.E);
                    result.setText(input);
                } else {
                    input = String.valueOf(Math.PI);
                    result.setText(input);
                }
            } else if (context.equals(".")) {
                String value = String.valueOf(result.getText());
                if (value.charAt(value.length() - 1) >= 47 && value.charAt(value.length() - 1) <= 58 && !value.equals("0")) {
                    input += ".";
                } else if (value.charAt(value.length() - 1) >= 47 && value.charAt(value.length() - 1) <= 58 && value.equals("0"))
                    input += "0.";
                result.setText(input);
            } else {
                input += context;
                result.setText(input);
            }

        }
    };

    //获取操作符的监听器
    private View.OnClickListener actionOperator = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String context = ((Button) view).getText().toString();
            String value = result.getText().toString();


            //分情况判断用户点击的操作符
            if (context.equals("C")) {
                result.setText("0");
                input = "";
            } else if ("(".equals(context) && value.charAt(value.length() - 1) != '.') {
                input += context;
                result.setText(input);
            } else if (")".equals(context)) {
                int index = 0;
                boolean haveLeft = false;
                while (index < value.length()) {
                    char ch = value.charAt(index);
                    if (ch == '(') {
                        haveLeft = true;
                        if (value.charAt(index - 1) == '^') {

                        }

                    }
                    index++;
                }

                if (haveLeft) {
                    input += context;
                    result.setText(input);
                }

            } else if ("Back".equals(context)) {
                
                if (value.length()>1){
                    input = input.substring(0, input.length() - 1);
                    result.setText(input);
                }else {
                    result.setText("0");
                    input = "";
                }

            } else if ("=".equals(context)) {
                Calculator cal = new Calculator();
                double res = cal.calculate(value);
                input = String.valueOf(res);
                result.setText(input);
            } else if (value.charAt(value.length() - 1) >= 47 && value.charAt(value.length() - 1) <= 58
                    || value.charAt(value.length() - 1) == '%') {
                //
                value += context;
                result.setText(value);
                input = value;
            }

        }


    };


    //获取函数的监听器
    private View.OnClickListener actionFunction = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int id = view.getId();
            String value = result.getText().toString();
            Calculator cal;

            switch (id) {

                case R.id.sci_squared:
                    cal = new Calculator();
                    if (cal.isNum(value)) {
                        double res = Math.pow(Double.parseDouble(value), 2);
                        result.setText(String.valueOf(res));

                    } else {
                        result.setText("只能对数字使用该函数");
                    }
                    input = "";
                    break;
                case R.id.sci_cube:
                    cal = new Calculator();
                    if (cal.isNum(value)) {
                        double res = Math.pow(Double.parseDouble(value), 3);
                        result.setText(String.valueOf(res));
                    } else
                        result.setText("只能对数字使用该函数");

                    input = "";
                    break;
                case R.id.sci_yPower:
                    cal = new Calculator();
                    if (cal.isNum(value)) {
                        result.setText(value + "^");
                    } else {

                    }
                    break;
                case R.id.sci_root:
                    cal = new Calculator();
                    if (cal.isNum(value)) {
                        double res = Math.pow(Double.parseDouble(value), 1 / 2);
                        result.setText(String.valueOf(res));
                    } else
                        result.setText("只能对数字使用该函数");

                    input = "";
                    break;
                case R.id.sci_yRoot:
                    break;
                case R.id.sci_factorial:
                    if (value.matches("^[0-9]+$")) {
                        //该计算器仅支持运算整数的阶乘
                        cal = new Calculator();
                        long res = cal.factorial(Integer.parseInt(value));
                        input = String.valueOf(res);
                        result.setText(input);


                    } else {
                        result.setText("只能对整数使用该函数");

                    }
                    input = "";
                    break;
                case R.id.sci_logarithmE:
                    //计算自然数对数
                    cal = new Calculator();
                    if (cal.isNum(value)) {
                        double res = Math.log(Double.parseDouble(value));
                        result.setText(String.valueOf(res));
                    } else
                        result.setText("只能对数字使用该函数");

                    input = "";
                    break;
                case R.id.sci_logarithm:
                    //计算以10为底的对数
                    cal = new Calculator();
                    if (cal.isNum(value)) {
                        double res = Math.log10(Double.parseDouble(value));
                        result.setText(String.valueOf(res));
                    } else
                        result.setText("只能对数字使用该函数");

                    input = "";
                    break;
                case R.id.sci_sin:
                    cal = new Calculator();
                    if (cal.isNum(value)){
                        double num = Math.toRadians(Double.parseDouble(value));
                        double res = Math.sin(num);
                        result.setText(String.valueOf(res));
                    } else
                        result.setText("只能对数字使用该函数");
                    input = "";
                    break;
                case R.id.sci_cos:
                    cal = new Calculator();
                    if (cal.isNum(value)){
                        double num = Math.toRadians(Double.parseDouble(value));
                        double res = Math.cos(num);
                        result.setText(String.valueOf(res));
                    } else
                        result.setText("只能对数字使用该函数");
                    input = "";
                    break;
                case R.id.sci_tan:
                    cal = new Calculator();
                    if (cal.isNum(value)){
                        double num = Math.toRadians(Double.parseDouble(value));
                        double res = Math.tan(num);
                        result.setText(String.valueOf(res));
                    } else
                        result.setText("只能对数字使用该函数");
                    input = "";
                    break;


            }


        }
    };


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.scientific_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }


    //初始化界面元素
    private void initView() {

        //获取界面元素
        btn[0] = findViewById(R.id.sci_0);
        btn[1] = findViewById(R.id.sci_1);
        btn[2] = findViewById(R.id.sci_2);
        btn[3] = findViewById(R.id.sci_3);
        btn[4] = findViewById(R.id.sci_4);
        btn[5] = findViewById(R.id.sci_5);
        btn[6] = findViewById(R.id.sci_6);
        btn[7] = findViewById(R.id.sci_7);
        btn[8] = findViewById(R.id.sci_8);
        btn[9] = findViewById(R.id.sci_9);
        add = findViewById(R.id.sci_add);
        sub = findViewById(R.id.sci_sub);
        mul = findViewById(R.id.sci_mul);
        div = findViewById(R.id.sci_div);
        equal = findViewById(R.id.sci_equal);
        square = findViewById(R.id.sci_squared);
        cube = findViewById(R.id.sci_cube);
        yPower = findViewById(R.id.sci_yPower);
        root = findViewById(R.id.sci_root);
        yRoot = findViewById(R.id.sci_yRoot);
        factorial = findViewById(R.id.sci_factorial);
        ln = findViewById(R.id.sci_logarithmE);
        log = findViewById(R.id.sci_logarithm);
        sin = findViewById(R.id.sci_sin);
        cos = findViewById(R.id.sci_cos);
        tan = findViewById(R.id.sci_tan);
        percent = findViewById(R.id.sci_percent);
        e = findViewById(R.id.sci_e);
        pi = findViewById(R.id.sci_pi);
        clear = findViewById(R.id.sci_clear);
        back = findViewById(R.id.sci_back);
        left = findViewById(R.id.sci_left);
        right = findViewById(R.id.sci_right);
        result = findViewById(R.id.sci_result);
        point = findViewById(R.id.sci_point);

        //为数字绑定监听器
        for (int i = 0; i < btn.length; i++) {
            btn[i].setOnClickListener(actionNum);
        }
        e.setOnClickListener(actionNum);
        pi.setOnClickListener(actionNum);
        point.setOnClickListener(actionNum);

        //为操作符绑定监听器
        add.setOnClickListener(actionOperator);
        sub.setOnClickListener(actionOperator);
        mul.setOnClickListener(actionOperator);
        div.setOnClickListener(actionOperator);
        left.setOnClickListener(actionOperator);
        right.setOnClickListener(actionOperator);
        percent.setOnClickListener(actionOperator);
        clear.setOnClickListener(actionOperator);
        back.setOnClickListener(actionOperator);
        equal.setOnClickListener(actionOperator);

        //为函数绑定监听器
        square.setOnClickListener(actionFunction);
        cube.setOnClickListener(actionFunction);
        yPower.setOnClickListener(actionFunction);
        root.setOnClickListener(actionFunction);
        yRoot.setOnClickListener(actionFunction);
        factorial.setOnClickListener(actionFunction);
        ln.setOnClickListener(actionFunction);
        log.setOnClickListener(actionFunction);
        sin.setOnClickListener(actionFunction);
        cos.setOnClickListener(actionFunction);
        tan.setOnClickListener(actionFunction);


    }


    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        Intent intent;
        switch (id) {
            case R.id.action_common:
                intent = new Intent(ScientificActivity.this, MainActivity.class);
                startActivity(intent);
                break;

            case R.id.scientific_transform_base:
                intent = new Intent(ScientificActivity.this, ConverterBaseActivity.class);
                startActivity(intent);
                break;
            case R.id.scientific_transform_currency:
                intent = new Intent(ScientificActivity.this, ConverterCurrencyActivity.class);
                startActivity(intent);
                break;
            case R.id.scientific_transform_length:
                intent = new Intent(ScientificActivity.this, ConverterLengthActivity.class);
                startActivity(intent);
                break;
            case R.id.scientific_transform_volume:
                intent = new Intent(ScientificActivity.this, ConverterVolumeActivity.class);
                startActivity(intent);
                break;
            case R.id.scientific_action_dateCal:
                intent = new Intent(this, DateActivity.class);
                startActivity(intent);
                break;
            case R.id.scientific_action_help:
                AlertDialog.Builder helpTxt = new AlertDialog.Builder(ScientificActivity.this);
                helpTxt.setMessage("这里是帮助文档\n本计算器由Dio开发").setTitle("Help");
                helpTxt.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
                helpTxt.show();

                break;

            case R.id.scientific_action_exit:
                intent = new Intent(this, MainActivity.class);
                intent.putExtra(MainActivity.EXIST, true);
                startActivity(intent);


        }


        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (menu != null) {
            if (menu.getClass().getSimpleName().equalsIgnoreCase("MenuBuilder")) {
                try {
                    Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    method.setAccessible(true);
                    method.invoke(menu, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        return super.onMenuOpened(featureId, menu);
    }


}